package com.cloudlibrary.controller;

import com.cloudlibrary.domain.Book;
import com.cloudlibrary.domain.User;
import com.cloudlibrary.entity.PageResult;
import com.cloudlibrary.entity.Result;
import com.cloudlibrary.service.impl.BookServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


@Controller
public class BookController {
    /*自动添加该类型类*/
    @Autowired
    private BookServiceImpl bookService;

    //查询最新上架的图书
    @RequestMapping("/book/selectNewbooks")
    public String selectNewbooks(HttpServletRequest request) {
        /*开始的页码*/
        Integer pageNum = 1;
        /*每页几行数据*/
        Integer pageSize = 5;
        PageResult pageResult = bookService.selectNewBooks(pageNum, pageSize);
        request.setAttribute("pageResult", pageResult);
        return "forward:/admin/books_new.jsp";
    }

    //根据id查询图书信息
    /*返回对象加上 @ResponseBody 注解，返回格式会自动转成json*/
    @RequestMapping("/book/findById")
    public @ResponseBody
    Result findById(String id) {
        Book book = bookService.findById(id);
        Result<Book> result = new Result<Book>();
        if (book != null) {
            result.setSuccess(true);
            result.setMessage("查询成功");
            result.setData(book);
        } else {
            result.setSuccess(false);
            result.setMessage("查询失败");
        }
        return result;
    }

    //借阅图书
    @RequestMapping("/book/borrowBook")
    public @ResponseBody
    Result borrowBook(Book book, HttpServletRequest request) {
        Book book1 = bookService.findById(book.getId().toString());
        /*设置借阅时间*/
        book1.setBorrowTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        /*设置借阅人*/
        HttpSession session = request.getSession();
        String borrower = (String) session.getAttribute("username");
        book1.setBorrower(borrower);
        /*设置借阅归还时间*/
        book1.setReturnTime(book.getReturnTime());
        /*设置借阅状态*/
        book1.setStatus("1");
        bookService.borrowBook(book1);

        Result<Book> result = new Result<Book>();
        if (book1 != null) {
            result.setSuccess(true);
            result.setMessage("借阅成功！");
            result.setData(book);
        } else {
            result.setSuccess(false);
            result.setMessage("借阅失败！");
        }
        return result;
    }

    //分页查询图书
    @RequestMapping("/book/search")
    public ModelAndView search(Book book, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        PageResult pageResult = bookService.search(book, pageNum, pageSize);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("books");
        //将查询到的数据存放在 ModelAndView的对象中
        modelAndView.addObject("pageResult", pageResult);
        //将查询的参数返回到页面，用于回显到查询的输入框中
        modelAndView.addObject("search", book);
        modelAndView.addObject("pageNum", pageNum);
        modelAndView.addObject("gourl", request.getRequestURI());
        return modelAndView;
    }

    //新增图书
    @ResponseBody
    @RequestMapping("/book/addBook")
    public Result addBook(Book book) {
        try {
            Integer count = bookService.addBook(book);
            if (count != 1) {
                return new Result(false, "新增图书失败!");
            }
            return new Result(true, "新增图书成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "新增图书失败!");
        }
    }

    /* 编辑图书信息*/
    @ResponseBody
    @RequestMapping("/book/editBook")
    public Result editBook(Book book) {
        try {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            //设置图书的上架时间
            book.setUploadTime(dateFormat.format(new Date()));
            Integer count = bookService.editBook(book);
            if (count != 1) {
                return new Result(false, "编辑失败!");
            }
            return new Result(true, "编辑成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "编辑失败!");
        }
    }

    // 查询当前借阅的图书
    @RequestMapping("/book/searchBorrowed")
    public ModelAndView searchBorrowed(Book book, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        //获取当前登录的用户
        User user = (User) request.getSession().getAttribute("USER_SESSION");
        PageResult pageResult = bookService.searchBorrowed(book, user, pageNum, pageSize);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("book_borrowed");
        //将查询到的数据存放在 ModelAndView的对象中
        modelAndView.addObject("pageResult", pageResult);
        //将查询的参数返回到页面，用于回显到查询的输入框中
        modelAndView.addObject("search", book);
        modelAndView.addObject("pageNum", pageNum);
        modelAndView.addObject("gourl", request.getRequestURI());
        return modelAndView;
    }

    /*归还图书*/
    @ResponseBody
    @RequestMapping("/book/returnBook")
    public Result returnBook(String id, HttpSession session) {
        // 获取当前登录的用户信息
        User user = (User) session.getAttribute("USER_SESSION");
        try {
            boolean flag = bookService.returnBook(id, user);
            if (!flag) {
                return new Result(false, "还书失败!");
            }
            return new Result(true, "还书确认中，请先到行政中心还书!");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "还书失败!");
        }
    }

    /*归还确认*/
    @ResponseBody
    @RequestMapping("/book/returnConfirm")
    public Result returnConfirm(String id) {
        try {
            Integer count = bookService.returnConfirm(id);
            if (count != 1) {
                return new Result(false, "确认失败!");
            }
            return new Result(true, "确认成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "确认失败!");
        }
    }


}
